package org.finesys.common.core.module;

import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.io.Serializable;

@Accessors(chain = true)
@Data
@NoArgsConstructor
public class R<T> implements Serializable {

    private int code;

    private T data;

    private String msg;

    private boolean success;


    public static <T> R<T> success() {
        return success(null);
    }

    public static <T> R<T> success(T data) {
        return success(data, null);
    }

    public static <T> R<T> success(T data, String msg) {
        return result(ResultCode.SUCCESS, msg, data, true);
    }

    public static <T> R<T> failed() {
        return result(ResultCode.FAIL, null, null, false);
    }

    public static <T> R<T> failed(String msg) {
        return result(ResultCode.FAIL, msg, null, false);
    }

    public static <T> R<T> failed(T data) {
        return result(ResultCode.FAIL, null, data, false);
    }

    public static <T> R<T> failed(String msg, T data) {
        return result(ResultCode.FAIL, msg, data, false);
    }

    public static <T> R<T> failed(int code, String msg) {
        return result(code, msg, null, false);
    }

    public static <T> R<T> judge(boolean status) {
        return status ? success() : failed();
    }

    public static <T> R<T> result(int code, String msg, T data) {
        boolean success = validSuccess(code);
        return result(code, msg, data, success);
    }

    public static <T> R<T> result(int code, String msg, T data, boolean success) {
        return new R<T>().setCode(code).setData(data).setMsg(msg).setSuccess(success);
    }

    public static boolean validSuccess(int code) {
        return code == ResultCode.SUCCESS;
    }

}
